import { createStore } from 'vuex'
import {UserControllerService} from "../../generated";
import ACCESS_ENUM from "@/access/accessEnum";
import createPersistedState from 'vuex-persistedstate';
import router from "@/router";
export default createStore({
  state: ()=>({
    loginUser:
        {
          userName:"未登录",
          userRole: ACCESS_ENUM.NOT_LOGIN,
        }
  }) ,
  getters: {
  },
  mutations: {
    setLoginUser(state, user) {
      state.loginUser = user;
    },
    updateUser(state, payload) {
      state.loginUser = payload;
    },
  },
  actions: {
    async fetchLoginUser({ commit,state }) {
      try {
        // 发起请求获取登录用户信息
        const response = await UserControllerService.getMeUsingGet(); // 请根据实际情况替换为你的后端接口

        if (response.code===200)
        // 提交 mutation 更新登录用户信息
        commit('setLoginUser', response.result);
        else {
          console.log("已改变")
          commit("updateUser",{
            ...state.loginUser,
            userRole: ACCESS_ENUM.NOT_LOGIN,
          })
        }
      } catch (error) {
        console.log("已改变")
        commit("updateUser",{
          ...state.loginUser,
          userRole: ACCESS_ENUM.NOT_LOGIN,
        })
        setTimeout(() => {
          router.push({ path: "/user/login" });
        }, 200);
        console.error('Error fetching login user:', error);
        // 在实际应用中，你可能需要处理错误，例如显示错误信息给用户
      }
    },
  },
  modules: {
  },
  plugins:[createPersistedState()]
})
